import { NetworkResponse } from '../base/NetworkResponse'
import { Chain, Interceptor } from './NetworkInterceptor'

/**
 *  超时拦截器
 */
export class TimeoutInterceptor implements Interceptor {
  private timeout: number

  constructor(timeout: number = 0) {
    this.timeout = timeout
  }

  intercept<R = any>(chain: Chain): Promise<NetworkResponse<R>> {
    if (this.timeout <= 0) {
      return chain.proceedI(chain.requestI())
    }

    return new Promise<NetworkResponse<R>>((resolve, reject) => {
      let stop = false
      setTimeout(() => {
        if (stop == true) {
          return
        }
        stop = true
        return reject()
      }, this.timeout)

      chain.proceedI(chain.requestI()).then((response) => {
        if (stop == true) {
          return
        }
        stop = true
        return resolve(response)
      }).catch((error) => {
        if (stop == true) {
          return
        }
        stop = true
        return reject(error)
      })
    })
  }
}